/*
 * Package il.ac.biu.cs.grossmm.api.presence
 * File Policy.java
 * 
 * This is a part of presence service framework API. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.api.presence;

import java.util.WeakHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Policy implements ResourceType {
	private final String name;

	private static final WeakHashMap<String, Policy> instances =
		new WeakHashMap<String, Policy>();

	private static final Lock lock = new ReentrantLock();

	/**
	 * Gets a policy resource type with a given name
	 * @param name name of this policy type
	 * @return
	 */
	public static Policy policy(String name)
	{
		Policy policy;

		lock.lock();

		try {
			policy = instances.get(name);

			if (policy == null) {
				policy = new Policy(name);
				instances.put(name, policy);
			}
		} finally {
			lock.unlock();
		}

		return policy;
	}

	private Policy(String name)
	{
		this.name = name;
	}

	String name()
	{
		return name;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (obj == this)
			return true;

		if (!(obj instanceof Policy))
			return false;

		Policy w = (Policy) obj;

		return w.name.equals(name);
	}

	@Override
	public int hashCode()
	{
		return 0x123abc ^ name.hashCode();
	}
	
	@Override
	public String toString()
	{
		return "POLICY("+name+")";
	}
}
